package com.llkj.qingnianguoxue.home;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.HotRankingAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.HotRankingBean;
import com.llkj.qingnianguoxue.bean.ResponseBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import java.util.ArrayList;
import java.util.List;

import static com.llkj.qingnianguoxue.home.JingXuanActivity.REQUEST_VIDEO_CODE;

/**
 * 范儿视频——精选欣赏，教学示范，订阅导师
 */
public class JingXuanVideoFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener{
    public static String VIDEO_TYPE = "video_type";

    private SwipeRefreshLayout refreshLayout;
    private RecyclerView lvActions;
    private HotRankingAdapter jingXuanAdapter;
    private List<HotRankingBean.RankingBean> mWenHuaData;
    private int totalSize,mPage,mCurrentPosition;
    private int mVideoType;
    private String mClassityId,mArtistId;
    /**
     *
     */
    public static JingXuanVideoFragment newInstance(int videoType,String tabId,String artistId) {
        JingXuanVideoFragment fragment = new JingXuanVideoFragment();
        Bundle args = new Bundle();
        args.putInt(VIDEO_TYPE, videoType);
        args.putString("classityId", tabId);
        args.putString("artistId", artistId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_jing_xuan_video, container, false);
        Bundle bundle = getArguments();
        mVideoType = bundle.getInt(VIDEO_TYPE);
        mClassityId = bundle.getString("classityId");
        mArtistId = bundle.getString("artistId");

        initView();
        initListener();

        onRefresh();
        return rootView;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.e("Log","======onHiddenChanged()======="+hidden);
    }

    private void initView() {
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvActions = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        int padding = DisplayUtil.dip2px(getActivity(), 10);
        lvActions.setPadding(padding, 0, padding, padding);
        lvActions.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        mWenHuaData = new ArrayList<>();
        jingXuanAdapter = new HotRankingAdapter(R.layout.item_hot_ranking, mWenHuaData, null);
        if(!StringUtils.isEmpty(mArtistId)){
            jingXuanAdapter.setType(5);
        }else{
            jingXuanAdapter.setType(1);
        }

        lvActions.setAdapter(jingXuanAdapter);
    }
    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
        jingXuanAdapter.setOnLoadMoreListener(this);
        lvActions.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                mCurrentPosition = position;
                HotRankingBean.RankingBean item =  mWenHuaData.get(mCurrentPosition);
                if(view.getId()== R.id.iv_add_shop){
                    if (1 == item.getType()) {
                        addCart(item.getId());
                    } else if (2 == item.getType() && !StringUtils.isEmpty(item.getShopping_id())) {
                        delCart(item.getShopping_id());
                    }
                }
            }
        });
        lvActions.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mCurrentPosition = i;
                HotRankingBean.RankingBean item =  mWenHuaData.get(mCurrentPosition);
                Bundle bundle = new Bundle();
                bundle.putString("id", item.getId());
                startActivityForResult(VideoDetailActivity.class, bundle, REQUEST_VIDEO_CODE);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        onRefresh();
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getJingXuanData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getJingXuanData();
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_VIDEO_LISTING) {
            HotRankingBean hotRankingBean = GsonUtil.GsonToBean(data, HotRankingBean.class);
            if (hotRankingBean != null) {

               try {
                   int mShopNum = Integer.parseInt(hotRankingBean.getShopping_num());
                   ((JingXuanActivity)getActivity()).setShopCount(mShopNum);
               }catch (Exception e){}

                totalSize = Integer.parseInt(hotRankingBean.getNum());
                if (mPage == 1) {
                    mWenHuaData.clear();
                    LoadDataHelper.refreshComplete(jingXuanAdapter, mWenHuaData, refreshLayout, lvActions);
                } else {
                    jingXuanAdapter.setEnableLoadMore(true);
                    jingXuanAdapter.loadMoreComplete();
                }

                if (hotRankingBean.getVideo() != null) {
                    mWenHuaData.addAll(hotRankingBean.getVideo());
                    jingXuanAdapter.notifyDataSetChanged();
                }else{
                    ToastUtil.makeLongText(getActivity(),"暂无此类视频");
                }
            }
        } else if (method == HttpMethod.HTTP_ORDER_ADD_SHOPPING) {//9.2视频/图书加购物车
            ResponseBean responseBean = GsonUtil.GsonToBean(data, ResponseBean.class);
            if (responseBean != null) {
                ToastUtil.makeLongText(getActivity(), "成功加入购物车");
                ((JingXuanActivity)getActivity()).changeShopCount(2);
                HotRankingBean.RankingBean item = mWenHuaData.get(mCurrentPosition);
                item.setShopping_id(responseBean.getShopping_id());
                item.setType(2);
                jingXuanAdapter.notifyItemChanged(mCurrentPosition);
            }
        } else if (method == HttpMethod.HTTP_USER_DEL_SHOPPING) {//8.13删除购物车商品
            ToastUtil.makeLongText(getActivity(), "成功移除购物车");
            ((JingXuanActivity)getActivity()).changeShopCount(1);
            HotRankingBean.RankingBean item = mWenHuaData.get(mCurrentPosition);
            item.setType(1);
            jingXuanAdapter.notifyItemChanged(mCurrentPosition);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, jingXuanAdapter, null, lvActions, totalSize);
    }

    /**
     * 获取精选视频数据
     */
    private void getJingXuanData() {
        HttpMethod.videoList(getActivity(), this, mClassityId,mArtistId, String.valueOf(mPage));
    }

    /**
     * 加入购物车
     */
    private void addCart(String videoId) {
        HttpMethod.addShopping(getActivity(), this, "1", videoId);
    }

    /**
     * 删除购物车
     */
    private void delCart(String cartId) {
        HttpMethod.delShopping(getActivity(), this, cartId,"2");
    }
}
